#!/bin/bash

set -e

CUR_DIR=$PWD
SRC_DIR=$PWD

if [ $# -eq 1 ]; then
    cmd=$1
elif [ $# -eq 2 ]; then
    cmd=$1
    path=$2
    if [ -d ${path} ]; then
        cd $path
    else
        echo "Invalid path: ${path}"
        exit 1
    fi
else
    echo "Invalid Parameters..."
    exit 1
fi

PKG_LIST=$(go list ./... | grep -v "protos" | grep -v "vendor" | grep -v "common/third" | grep -v "jvm.go" | grep -v "store/db/es" \
    | grep -v "store/mq/rabbitmq")
LINT_VER=v0.0.0-20190409202823-959b441ac422

# Code coverage generation
function coverage_test() {
    COVERAGE_DIR="${COVERAGE_DIR:-build_coverage}"
    mkdir -p "$COVERAGE_DIR"

    go test -gcflags=all=-l -coverprofile ${COVERAGE_DIR}/coverage.data ${PKG_LIST}

    # If needed, generate HTML report
    if [ "$1" == "html" ]; then
        go tool cover -html=${COVERAGE_DIR}/coverage.data -o coverage.html
    fi
}

function coverage_stat() {
    COVERAGE_DIR="${COVERAGE_DIR:-build/coverage}"

    if [ -f ${COVERAGE_DIR}/coverage.data ]; then
        go tool cover -func=${COVERAGE_DIR}/coverage.data
    fi
}

function report_coverage() {
    go tool cover -func=build_coverage/coverage.data
}

function ineffassign_check() {
    golangci-lint run --no-config --issues-exit-code=1 --deadline=2m --disable-all --enable=ineffassign ./...
}

case $cmd in
    lint) for dir in ${PKG_LIST}; do golint $dir; done ;;
    test) go test -gcflags=all=-l -short ${PKG_LIST} ;;
    race) go test -gcflags=all=-l -v -race -short ${PKG_LIST} ;;
    coverage) coverage_test && coverage_stat ;;
    coverhtml) coverage_test html ;;
    coveragestat) report_coverage ;;
    vet) go vet ${PKG_LIST} ;;
    ineffassign) ineffassign_check ;;
    build) dep && go build ./... ;;
    clean) rm -rf ${PKG_LIST} && git checkout . ;;
esac
cd $CUR_DIR
